package day01;

import java.util.Iterator;

/**
 * @author Jetwang
 * @version 1.0
 * @since 2023/2/27 20:49
 */
public class CircleLinkedListSentinel implements Iterable<Integer> {
    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node p = dummy.next;
            @Override
            public boolean hasNext() {
                return p != dummy;
            }

            @Override
            public Integer next() {
                int v = p.value;
                p = p.next;
                return v;
            }
        };
    }

    private static class Node {
        Node prev;
        int value;
        Node next;

        public Node(Node prev, int value, Node next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }

    private Node dummy = new Node(null, 666, null);

    public CircleLinkedListSentinel() {
        dummy.next = dummy;
        dummy.prev = dummy;
    }

    public void addFirst(int value) {
        Node a = dummy;
        Node b = dummy.next;
        Node added = new Node(a, value, b);
        a.next = added;
        b.prev = added;
    }

    public void addLast(int value) {
        Node b = dummy;
        Node a = dummy.prev;
        Node added = new Node(a, value, b);
        a.next = added;
        b.prev = added;
    }

    public void removeFirst() {
        Node removed = dummy.next;
        if (removed == dummy) {
            throw new RuntimeException("没有删除的节点!");
        }
        Node a = removed.prev;
        Node b = removed.next;
        a.next = b;
        b.prev = a;
    }

    public void removeLast() {
        Node removed = dummy.prev;
        if (removed == dummy) {
            throw new RuntimeException("没有删除的节点!");
        }
        Node a = removed.prev;
        Node b = dummy;
        a.next = b;
        b.prev = a;
    }

    public void removeByValue(int value) {
        Node removed = findByValue(value);
        if (removed == null) {
            throw new RuntimeException("没有该值的节点!");
        }
        Node a = removed.prev;
        Node b = removed.next;
        a.next = b;
        b.prev = a;
    }

    private Node findByValue(int value) {
        Node p = dummy.next;
        while(p != dummy) {
            if (p.value == value) {
                return p;
            }
            p = p.next;
        }
        return null;
    }
}
